package com.zzxy.zzxy.spring2.factory;

import com.zzxy.zzxy.spring2.aspect.MyAspect;
import com.zzxy.zzxy.spring2.service.IStudentService;
import com.zzxy.zzxy.spring2.service.impl.StudentServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyBeanFactory {
    public static IStudentService createStudentService() {
        //1.target class
        StudentServiceImpl studentService = new StudentServiceImpl();
        //2.advice
        MyAspect myAspect = new MyAspect();
        //3.weaving
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(studentService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                myAspect.before();
                Object obj = methodProxy.invokeSuper(o, objects);
                myAspect.after();
                return null;
            }
        });
        return (StudentServiceImpl) enhancer.create();
    }
}
